import React, { useEffect, useState } from 'react';
import { Button } from 'tdesign-react';

const BacktopIcon = (props) => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} {...props}>
    <path d="M12 19V5M5 12l7-7 7 7" />
  </svg>
);

const BackToTop = () => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      setVisible(window.scrollY > 300);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (!visible) return null;

  return (
    <div
      style={{
        position: 'fixed',
        right: 24,
        bottom: 24,
        zIndex: 1100,
      }}
    >
      <Button
        shape="round"
        variant="outline"
        icon={<BacktopIcon />}
        onClick={scrollToTop}
        style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--border)' }}
      />
    </div>
  );
};

export default BackToTop;